package vertx;


import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.*;

import java.util.ArrayList;

/**
 * @author 今何许
 * @date 2021-01-11 14:49
 */
public class MysqlVerticle extends AbstractVerticle {

  //配置连接参数
  MySQLConnectOptions connectOptions = new MySQLConnectOptions()
    .setPort(3306)
    .setHost("localhost")
    .setDatabase("vertx")
    .setUser("root")
    .setPassword("123456");

  //配置连接池 Pool options
  PoolOptions poolOptions = new PoolOptions()
    .setMaxSize(5);

  // Create the client pool
  MySQLPool client;

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    //创建一个数据库连接
    client = MySQLPool.pool(vertx, connectOptions, poolOptions);

    // Create a Router
    Router router = Router.router(vertx);

    //获取body参数，添加这句话
    router.route().handler(BodyHandler.create());

    //根据id查询
    router.route("/query/:id").handler(req -> {
      String id = req.request().getParam("id");
      client.getConnection(arr1 -> {
        if (arr1.succeeded()) {
          SqlConnection connection = arr1.result();
          connection.preparedQuery("select * from user where id=?")
            .execute(Tuple.of(id),arr2 -> {
              connection.close();
              if (arr2.succeeded()) {
                ArrayList<JsonObject> list = new ArrayList<>();
                RowSet<Row> rows = arr2.result();
                rows.forEach(row -> {
                  JsonObject entries = new JsonObject();
                  entries.put("id", row.getValue("id"))
                    .put("name", row.getValue("name"));
                  list.add(entries);
                });
                req.response().putHeader("content-type", "application/json")
                  .end(list.toString());
              } else {
                req.response().putHeader("content-type", "application/json")
                  .end(arr2.cause().toString());
              }
            });
        } else {

        }
      });
    });


    //绑定路由
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}

